<template>
  <div class="car-details">
    <el-page-header @back="goBack" content="车辆详情"></el-page-header>

    <el-card class="car-info-card" v-loading="loading">
      <div v-if="carDetails && carDetails.length > 0">
        <!-- 循环展示每个车辆详情 -->
        <div
          v-for="(detail, index) in carDetails"
          :key="detail.cdid"
          class="car-detail-item"
        >
          <el-divider v-if="index > 0"></el-divider>
          <h3>车辆详情 #{{ index + 1 }}</h3>

          <el-row :gutter="20" class="car-detail-row">
            <!-- 左侧图片轮播 -->
            <el-col :span="12" class="image-col">
              <div class="car-image-slider" style="width: 780px">
                <el-carousel height="400px" indicator-position="outside">
                  <el-carousel-item
                    v-for="(photo, photoIndex) in detail.photos"
                    :key="photoIndex"
                  >
                    <el-image
                      style="width: 100%; height: 100%"
                      :src="photo.cpimg"
                      :preview-src-list="getPhotoList(detail)"
                      :initial-index="photoIndex"
                      fit="cover"
                      lazy
                    ></el-image>
                  </el-carousel-item>
                </el-carousel>
              </div>
              <div class="bnt">
                <el-button type="success" @click="handleAction(detail)">{{
                  isAdmin() == true ? "修改详情" : "立即下单"
                }}</el-button>
              </div>
            </el-col>

            <!-- 右侧车辆信息 -->
            <el-col :span="12" class="info-col">
              <el-descriptions :column="1" border class="car-info-descriptions">
                <el-descriptions-item label="生产年份">
                  {{ detail.productyear }}
                </el-descriptions-item>
                <el-descriptions-item label="车辆等级">
                  {{ detail.level }}
                </el-descriptions-item>
                <el-descriptions-item label="座位数">
                  {{ detail.seats }}
                </el-descriptions-item>
                <el-descriptions-item label="车门数">
                  {{ detail.doors }}
                </el-descriptions-item>
                <el-descriptions-item label="能源类型">
                  {{ getEnergyTypeName(detail.energyid) }}
                </el-descriptions-item>
                <el-descriptions-item label="变速箱类型">
                  {{ detail.gearName || getGearTypeName(detail.gearid) }}
                </el-descriptions-item>
                <el-descriptions-item label="排量">
                  {{ detail.displacement }}
                </el-descriptions-item>
                <el-descriptions-item label="驱动方式">
                  {{ getDriveTypeName(detail.drive) }}
                </el-descriptions-item>
                <el-descriptions-item label="电动天窗">
                  <el-tag :type="detail.upwindow === 1 ? 'success' : 'info'">
                    {{ detail.upwindow === 1 ? "有" : "无" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="倒车雷达">
                  <el-tag :type="detail.radar === 1 ? 'success' : 'info'">
                    {{ detail.radar === 1 ? "有" : "无" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="GPS导航">
                  <el-tag :type="detail.gps === 1 ? 'success' : 'info'">
                    {{ detail.gps === 1 ? "有" : "无" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="驾照要求">
                  <el-tag :type="detail.lisence === 1 ? 'success' : 'info'">
                    {{ detail.lisence === 1 ? "需要" : "不需要" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否在线">
                  <el-tag :type="detail.isonline === 1 ? 'success' : 'info'">
                    {{ detail.isonline === 1 ? "在线" : "离线" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否删除">
                  <el-tag :type="detail.isdeleted === 0 ? 'success' : 'danger'">
                    {{ detail.isdeleted === 0 ? "未删除" : "已删除" }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </div>
      </div>

      <div v-else-if="!loading" class="no-data">
        <el-empty description="暂无车辆详情数据"></el-empty>
      </div>
    </el-card>

    <!-- 修改车辆详情弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改车辆详情"
      width="60%"
      :before-close="handleClose"
    >
      <el-form
        :model="editForm"
        label-width="120px"
        ref="editFormRef"
        v-loading="editLoading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产年份" prop="productyear">
              <el-input v-model="editForm.productyear"></el-input>
            </el-form-item>
            <el-form-item label="车辆等级" prop="level">
              <el-input v-model="editForm.level"></el-input>
            </el-form-item>
            <el-form-item label="座位数" prop="seats">
              <el-input-number
                v-model="editForm.seats"
                :min="1"
                :max="10"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="车门数" prop="doors">
              <el-input-number
                v-model="editForm.doors"
                :min="1"
                :max="10"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="能源类型" prop="energyid">
              <el-select
                v-model="editForm.energyid"
                placeholder="请选择能源类型"
              >
                <el-option
                  v-for="(name, id) in energyTypes"
                  :key="id"
                  :label="name"
                  :value="parseInt(id)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="变速箱类型" prop="gearid">
              <el-select
                v-model="editForm.gearid"
                placeholder="请选择变速箱类型"
              >
                <el-option
                  v-for="(name, id) in gearTypes"
                  :key="id"
                  :label="name"
                  :value="parseInt(id)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排量" prop="displacement">
              <el-input v-model="editForm.displacement"></el-input>
            </el-form-item>
            <el-form-item label="驱动方式" prop="drive">
              <el-select v-model="editForm.drive" placeholder="请选择驱动方式">
                <el-option
                  v-for="(name, id) in driveTypes"
                  :key="id"
                  :label="name"
                  :value="parseInt(id)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="电动天窗" prop="upwindow">
              <el-switch
                v-model="editForm.upwindow"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="倒车雷达" prop="radar">
              <el-switch
                v-model="editForm.radar"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="GPS导航" prop="gps">
              <el-switch
                v-model="editForm.gps"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="驾照要求" prop="lisence">
              <el-switch
                v-model="editForm.lisence"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitEditForm"
            :loading="editLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 下单弹窗 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="预订车辆"
      width="50%"
      :before-close="handleCloseOrder"
    >
      <el-form
        :model="orderForm"
        label-width="120px"
        ref="orderFormRef"
        v-loading="orderLoading"
      >
        <el-form-item label="开始时间" prop="starttime">
          <el-date-picker
            v-model="orderForm.starttime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endtime">
          <el-date-picker
            v-model="orderForm.endtime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitOrderForm"
            :loading="orderLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "@/util/service";
import { ElMessage, ElMessageBox } from "element-plus";
import { useLoginStore } from "@/stores/userStores";

const userStore = useLoginStore();
const route = useRoute();
const router = useRouter();
const isAdmin = () => {
  if (userStore.getId != 1) {
    return false;
  } else {
    return true;
  }
};
console.log(isAdmin);
// 车辆详情数据（数组）
const carDetails = ref([]);
const loading = ref(false);

// 修改表单相关
const editDialogVisible = ref(false);
const editForm = ref({
  cdid: 0,
  productyear: "",
  level: "",
  seats: 0,
  doors: 0,
  energyid: 0,
  gearid: 0,
  displacement: "",
  drive: 0,
  upwindow: 0,
  radar: 0,
  gps: 0,
  lisence: 0,
});
const editLoading = ref(false);
const editFormRef = ref(null);

// 能源类型映射
const energyTypes = {
  1: "汽油",
  2: "柴油",
  3: "电动",
  4: "混合动力",
};

// 变速箱类型映射
const gearTypes = {
  1: "手动",
  2: "自动",
};

// 驱动方式映射
const driveTypes = {
  1: "前驱",
  2: "后驱",
  3: "四驱",
};

// 获取能源类型名称
const getEnergyTypeName = (energyId) => {
  return energyTypes[energyId] || "未知";
};

// 获取变速箱类型名称
const getGearTypeName = (gearId) => {
  return gearTypes[gearId] || "未知";
};

// 获取驱动方式名称
const getDriveTypeName = (driveId) => {
  return driveTypes[driveId] || "未知";
};

// 获取指定详情的图片列表用于预览
const getPhotoList = (detail) => {
  if (detail && detail.photos) {
    return detail.photos.map((photo) => photo.cpimg);
  }
  return [];
};

// 获取车辆详情
const fetchCarDetails = async () => {
  const carId = sessionStorage.getItem("carId");
  if (!carId) {
    ElMessage.error("车辆ID不能为空");
    return;
  }

  loading.value = true;
  try {
    const response = await api.get("/tcar/selectcardetail", {
      params: {
        carId: carId * 1,
      },
    });

    if (response.code === 200 && response.data) {
      carDetails.value = response.data; // 直接赋值整个数组
    } else {
      ElMessage.error("获取车辆详情失败");
    }
  } catch (error) {
    console.error("获取车辆详情失败:", error);
    ElMessage.error("获取车辆详情失败");
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 处理按钮点击事件
const handleAction = (detail) => {
  if (isAdmin()) {
    // 管理员：修改详情
    openEditDialog(detail);
  } else {
    // 普通用户：立即下单
    openOrderDialog(detail);
  }
};

// 打开修改详情弹窗
const openEditDialog = (detail) => {
  editForm.value = { ...detail };
  const { photos, ...editData } = detail;
  editForm.value = { ...editData };
  editDialogVisible.value = true;
};

// 提交修改表单
const submitEditForm = async () => {
  editLoading.value = true;
  try {
    const response = await api.post("/tcar/updateCarDetail", editForm.value);

    if (response.code === 200) {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      fetchCarDetails(); // 重新获取数据
    } else {
      ElMessage.error("修改失败：" + response.message);
    }
  } catch (error) {
    console.error("修改失败:", error);
    ElMessage.error("修改失败，请稍后重试");
  } finally {
    editLoading.value = false;
  }
};
// 下单弹窗相关
const orderDialogVisible = ref(false);
const orderForm = ref({
  userid: userStore.getId,
  cdid: 0,
  starttime: "",
  endtime: "",
  remark: "",
});
const orderLoading = ref(false);
const orderFormRef = ref(null);

// 打开下单弹窗
const openOrderDialog = (detail) => {
  orderForm.value = {
    userid: userStore.getId,
    cdid: detail.cdid,
    starttime: "",
    endtime: "",
    remark: "",
  };
  orderDialogVisible.value = true;
};
// 提交订单表单
const submitOrderForm = async () => {
  orderLoading.value = true;
  try {
    const response = await api.post("/tbookcar/insertBookcar", orderForm.value);

    if (response.code === 200) {
      ElMessage.success("预订成功！");
      orderDialogVisible.value = false;
    } else {
      ElMessage.error("预订失败：" + response.message);
    }
  } catch (error) {
    console.error("预订失败:", error);
    ElMessage.error("预订失败，请稍后重试");
  } finally {
    orderLoading.value = false;
  }
};

// 关闭下单弹窗前确认
const handleCloseOrder = (done) => {
  ElMessageBox.confirm("确认关闭？已填写的内容将不会保存")
    .then(() => {
      done();
    })
    .catch(() => {
      // 用户取消关闭
    });
};
// 关闭弹窗前的确认
const handleClose = (done) => {
  ElMessageBox.confirm("确认关闭？修改的内容将不会保存")
    .then(() => {
      done();
    })
    .catch(() => {
      // 用户取消关闭
    });
};

onMounted(() => {
  fetchCarDetails();
  // 用户身份
});
</script>

<style scoped>
html,
body {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}

.car-details {
  padding: 20px;
  overflow-y: auto;
}

.car-info-card {
  margin-top: 20px;
}

.car-image-slider {
  text-align: center;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

.el-carousel__item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-image {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.car-detail-item {
  margin-top: 30px;
  margin-bottom: 30px;
}

.car-detail-item:last-child {
  margin-bottom: 0;
}

.car-detail-item h3 {
  margin-bottom: 15px;
  color: #409eff;
}

.car-detail-row {
  margin-bottom: 30px;
}

.image-col {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.info-col {
  display: flex;
  align-items: center;
}

.car-info-descriptions {
  width: 100%;
}

.bnt {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
